package com.itheima.grow.util;

import lombok.Cleanup;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
 * 生成压缩流工具类
 */
public class ZipUtil {

    public static void createZipFile(List<String> fileUrls, HttpServletResponse response) throws IOException {
        //zip包的名称
        String downloadFilename ="DZ"+DateUtil.formatDate(new Date(),DateUtil.FORMAT_5)+".zip";
        downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);
        @Cleanup ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
        fileUrls.forEach(i->{
            InputStream fis = null;
            try {
                String[] split = i.split("/");
                String fileName = split[split.length - 1];
                ZipEntry zipEntry = new ZipEntry(fileName);
                zos.putNextEntry(zipEntry);
                fis = getInputStreamByUrl(i);
                if (null != fis) {
                    byte[] buffer = new byte[1024];
                    int r = 0;
                    while ((r = fis.read(buffer)) != -1) {
                        zos.write(buffer, 0, r);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private static InputStream getInputStreamByUrl(String url) throws IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        return conn.getInputStream();
    }
}
